
import Vue from "vue";
import $ from "jquery";

import {wifi,NetWorkState} from "../hos/wifi.js";
import {Udp, UdpDataFormat} from "../hos/udp.js";

import {Activity} from "./activity.js";

class UdpTest extends Activity{

    onCreate() {
        super.onCreate();

        $(this.find("log")).append("WiFi信息:" + JSON.stringify(wifi.currentApInfo()) + "<br>");

        new Vue({
            el: this.find("connect"),
            methods: {
                click: ()=> {
                    this.connectDevice();
                }
            }});
    }

    connectDevice() {

        this.close();

        alert("创建udp");

        this.udpClientForDevice = new Udp();
        this.udpClientForDevice.addRecvObserver((event)=>{
            let packet = event.data;
            this.udpClientForDevice.send(packet.data, packet.remoteIp, packet.remotePort, UdpDataFormat.TEXT);
        });

        // this.udpClientForDevice.send('hello udp', '192.168.124.9', 8085, UdpDataFormat.TEXT)
        this.udpClientForDevice.bind(10000, UdpDataFormat.TEXT).then(()=>{
            alert("绑定端口成功");
            this.udpClientForDevice.send("hello udp", "255.255.255.255", 8085, UdpDataFormat.TEXT);
        }).catch((error)=>{alert(error.errMsg);});
    }


    close() {
        if (this.udpClientForDevice) {
            this.udpClientForDevice.destroy();
            this.udpClientForDevice = null;
        }

    }

    onResume() {
        super.onResume();
        // 监听网络状态变化
        wifi.addNetWorkStateObserver(this.stateObserver, this);
    }

    onPause() {
        super.onPause();

        // 移除网络状态变化监听
        wifi.removeNetWorkStateObserver(this.stateObserver);

        this.close();

    }

}

export {UdpTest};
